﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using YiSha.Util;
using YiSha.Util.Model;
using YiSha.Entity;
using YiSha.Model;
using YiSha.Admin.Web.Controllers;
using YiSha.Entity.QixingManage;
using YiSha.Business.QixingManage;
using YiSha.Model.Param.QixingManage;
using YiSha.Model.Result.QixingManage;
using YiSha.Enum.QixingManage;
using YiSha.Util.Extension;
using Newtonsoft.Json;
using YiSha.IdGenerator;
using YiSha.Web.Code;
using YiSha.Service.QixingManage;

namespace YiSha.Admin.Web.Areas.QixingManage.Controllers
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2023-04-29 21:16
    /// 描 述：退货申请处理控制器类
    /// </summary>
    [Area("QixingManage")]
    public class OrderRefundApplyController :  BaseController
    {
        private OrderRefundApplyBLL orderRefundApplyBLL = new OrderRefundApplyBLL();

        private ShopBLL shopBLL = new ShopBLL();

        private GoodsBLL goodsBLL = new GoodsBLL();

        private OrderMasterBLL OrderMasterBLL = new OrderMasterBLL();

        private OrderDetailBLL orderDetailBLL = new OrderDetailBLL();

        #region 视图功能
        [AuthorizeFilter("qixing:orderrefundapply:view")]
        public ActionResult OrderRefundApplyIndex()
        {
            return View();
        }

        public ActionResult OrderRefundApplyForm()
        {
            return View();
        }
        #endregion

        #region 获取数据
        [HttpGet]
        [AuthorizeFilter("qixing:orderrefundapply:search")]
        public async Task<ActionResult> GetListJson(OrderRefundApplyListParam param)
        {
            OperatorInfo operatorInfo = await Operator.Instance.Current();
            if (operatorInfo.IsSystem == 0)
            {
                param.tenant_id = operatorInfo.tenant_id;
            }
            TData<List<OrderRefundApplyEntity>> obj = await orderRefundApplyBLL.GetList(param);
            return Json(obj);
        }

        [HttpGet]
        [AuthorizeFilter("qixing:orderrefundapply:search")]
        public async Task<ActionResult> GetPageListJson(OrderRefundApplyListParam param, Pagination pagination)
        {
            OperatorInfo operatorInfo = await Operator.Instance.Current();
            if (operatorInfo.IsSystem == 0)
            {
                param.tenant_id = operatorInfo.tenant_id;
            }
            TData<List<OrderRefundApplyEntity>> obj = await orderRefundApplyBLL.GetPageList(param, pagination);
            return Json(obj);
        }

        [HttpGet]
        public async Task<ActionResult> GetFormJson(long id)
        {
            TData<OrderRefundApplyEntity> obj = await orderRefundApplyBLL.GetEntity(id);
            return Json(obj);
        }

        [HttpGet]
        public async Task<ActionResult> GetOrderRefundApplyFormJson(long id)
        {
            TData<OrderRefundApplyDto> obj = await orderRefundApplyBLL.GetOrderRefundApplyFormJson(id);
            return Json(obj);
        }
        #endregion

        #region 提交数据
        [HttpPost]
        [AuthorizeFilter("qixing:orderrefundapply:add,qixing:orderrefundapply:edit")]
        public async Task<ActionResult> SaveFormJson(OrderRefundApplyEntity entity)
        {
            TData<string> obj = await orderRefundApplyBLL.SaveForm(entity);
            return Json(obj);
        }

        [HttpPost]
        [AuthorizeFilter("qixing:orderrefundapply:delete")]
        public async Task<ActionResult> DeleteFormJson(string ids)
        {
            TData obj = await orderRefundApplyBLL.DeleteForm(ids);
            return Json(obj);
        }

        [HttpPost]
        [AuthorizeFilter("qixing:orderrefundapply:edit")]
        public async Task<ActionResult> SaveOrderRefundApplyFormJson(OrderRefundApplyEntity entity)
        {
            TData<OrderRefundApplyEntity> obj = await orderRefundApplyBLL.GetEntity(entity.Id.Value);

            if (obj.Tag == 1)
            {
                var data = obj.Data;
                if (data.status == 0)
                {
                    data.status = entity.status;
                    TData<string> res = await orderRefundApplyBLL.SaveForm(data);
                    return Json(res);
                }
                //确认退款
                if (entity.status == 2)
                {
                    if (data.refundType != 8)
                    {
                        //更新库存
                        //订单查询
                        var orderDetails = await orderDetailBLL.GetList(data.orderid.Value);

                        foreach (var item in orderDetails)
                        {
                            //GoodsAttrService goodsAttrService=new GoodsAttrService();

                            //var attr=await goodsAttrService.GetEntity(item.colorid.Value);

                            //if (attr!=null)
                            //{
                            //    attr.count = attr.count + item.goods_cnt.Value;

                            //    await goodsAttrService.SaveForm(attr);
                            //}
                            //还库存
                            GoodsSkuStockService goodsSkuStockService = new GoodsSkuStockService();

                            var attrsku = await goodsSkuStockService.GetEntity(item.skuid);

                            if (attrsku != null)
                            {
                                attrsku.stock = attrsku.stock + item.goods_cnt.Value;

                                await goodsSkuStockService.SaveForm(attrsku);
                            }
                        }
                    }
                    if (!data.goodsid.IsNullOrZero())
                    {
                        //查看商品
                        var goods = goodsBLL.GetEntity(data.goodsid.Value).Result;

                        if (goods.Tag == 1)
                        {
                            var goodsinfo = goods.Data;
                            //微信才调用退款
                            if (goodsinfo != null )
                            {
                                //查看商铺
                                var shopinfo = shopBLL.GetEntity(goodsinfo.shop_id.Value).Result.Data;
                                //订单查询
                                var orderinfo = OrderMasterBLL.GetEntity(data.orderid.Value).Result.Data;

                                if (data.paysource == 5) {
                                    //发起退款
                                    string url1 = GlobalContext.SystemConfig.WebApiSite + "/api/wechatpay/v3/Refund";
                                    RefundOrderApiFromPost fromPost = new RefundOrderApiFromPost();
                                    if (!orderinfo.ordernumber.IsEmpty())
                                    {
                                        fromPost.transactionId = orderinfo.ordernumber;
                                        fromPost.outTradeNo = orderinfo.order_sn.Value.ToString();
                                        fromPost.refundAmount = entity.amount.Value;
                                        fromPost.totalAmount = entity.product_real_price.Value;
                                        fromPost.outRefundNo = IdGeneratorHelper.Instance.GetId().ToString();
                                        fromPost.openid = data.openid;
                                        var postjson1 = System.Text.Json.JsonSerializer.Serialize(fromPost);
                                        var body = HttpHelper.Post(postjson1, url1);

                                        var dec = System.Text.Json.JsonSerializer.Deserialize<RefundOrderBody>(body);

                                        data.status = entity.status;
                                        data.amount = entity.amount;
                                        data.processnote = entity.processnote;
                                        data.outRefundNo = fromPost.outRefundNo;
                                        TData<string> res = await orderRefundApplyBLL.SaveForm(data);

                                        if (dec.success == true)
                                        {
                                            //发送订单退款通知
                                            string url2 = GlobalContext.SystemConfig.WebApiSite + "/WxApplet/SendSubscribeMessage";
                                            SendSubscribeMessageApiFromPost postdata = new SendSubscribeMessageApiFromPost();
                                            postdata.msgType = ((int)msgType.退款通知);
                                            postdata.money = entity.amount.ToString();
                                            postdata.time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            postdata.phone = shopinfo.phone_number;
                                            postdata.note = entity.processnote;
                                            postdata.status = "退款成功";
                                            var postjson2 = System.Text.Json.JsonSerializer.Serialize(postdata);
                                            HttpHelper.Post(postjson2, url2);
                                        }
                                        return Json(res);
                                    }
                                }
                                if (data.paysource ==2) {
                                    //余额
                                    UmsMemberService umsMemberService = new UmsMemberService();
                                    var  umsMember=umsMemberService.GetUserIdByEntity(orderinfo.customer_id.Value).Result;
                                    umsMember.money = umsMember.money + entity.amount.Value;
                                    await umsMemberService.SaveForm(umsMember);
                                    TData<string> res = new TData<string>();
                                    res.Data = "退款成功";
                                    res.Tag = 1;
                                    return Json(res);
                                }
                            }
                        }
                    }
                }
                else
                {
                    data.status = entity.status;
                    TData<string> res = await orderRefundApplyBLL.SaveForm(data);
                    return Json(res);
                }
            }
            else
            {
                obj.Tag = 0;
            }
            return Json(obj);
        }

        
        #endregion
    }
}
